package com.erp.erp_mask.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.erp.erp_mask.mapper.TRolePermissionsMapper;
import com.erp.erp_mask.pojo.TPermissions;
import com.erp.erp_mask.service.TPermissionsService;
import com.erp.erp_mask.vo.Result;
import com.erp.erp_mask.vo.TreeData;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @BelongsProject: erp
 * @BelongsPackage: com.erp.erp_mask.controller
 * @Author: wang
 * @CreateTime: 2024-05-08  17:41
 * @Description: TODO
 * @Version: 1.0
 * @effect:
 */
@RestController
@RequestMapping("/perm")
public class TPermissionsController {
    @Resource
    private TPermissionsService tPermissionsService;
    @Resource
    private TRolePermissionsMapper tRolePermissionsMapper;

    @GetMapping("/index")
    public ModelAndView index() {
        return new ModelAndView("/sys/permission");
    }

    @GetMapping("/searchTperlist")
    public Result searchTperlist(Integer parentId){
        return Result.success(tPermissionsService.searchTperlist());
    }
    @GetMapping("/searchPermid")
    public Result searchPermid() {
        return Result.success(tPermissionsService.searchPermid());
    }

    @GetMapping("/searchsort")
    public Result searchsort(Integer parid) {
        return Result.success(tPermissionsService.searchSort(parid));
    }

    @PostMapping("/addList")
    public Result addList(@RequestBody TPermissions tPermissions) {
        try {
            tPermissionsService.addList(tPermissions);
            return Result.success("添加成功!");
        } catch (Exception e) {
            return Result.fail("添加失败!");
        }
    }

    @PutMapping("/updList")
    public Result update(@RequestBody TPermissions tPermissions) {
        try {
            tPermissionsService.updateById(tPermissions);
            return Result.success("修改成功！");
        } catch (Exception e) {
            return Result.fail("修改失败!");
        }
    }

    @DeleteMapping("/delList")
    public Result delsearch(Long permissionId) {
        LambdaQueryWrapper<TPermissions> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TPermissions::getParentId, permissionId);
        List<TPermissions> list = tPermissionsService.list(wrapper);
        if (list.size() > 0) {
            return Result.success("父级下有子级存在，删除失败!");
        } else {
            return del(permissionId);
        }
    }

    @Transactional
    public Result del(Long permissionId) {
        try {
            tRolePermissionsMapper.deleteByPermissionId(permissionId);
            tPermissionsService.removeById(permissionId);
            return Result.success("删除成功！");
        } catch (Exception ex) {
            return Result.fail("删除失败！");
        }
    }
}
